#!/bin/bash -e
# 
# File: autossh.sh
# Purpose: run autossh for each tunnel site, if not already running
#

cd $(dirname "$0")
. ./common.sh

test "$1" && tunnelsites="$@" || tunnelsites=$(./sites.sh)

export AUTOSSH_PIDFILE=/var/run/autossh.pid
export AUTOSSH_PORT=0
tunnelSrcDir=${INSTALLDIR}/${config_dir}; 
tunnelDoingDir=${INSTALLDIR}/${config_doing_dir}; 

for tunnelsite in $tunnelsites; do
    tunnel_name=`echo ${tunnelsite} | cut -d = -f 1`;
    tunnel_comment=`echo ${tunnelsite} | cut -d = -f 2 | sed -e 's/_/ /g'`;
	info 'open ['$tunnel_name'] ssh tunnel'
    # stop running session
    if ! match_session $tunnel_name | awk '$0 !~ /tached/ { exit 1 }'; then
        ./stop-screen.sh $tunnel_name
    fi
	
    if ! match_session $tunnel_name >/dev/null; then
        info 'starting autossh '$tunnel_name '...'	
        screen -d -m -S $tunnel_name autossh -M $AUTOSSH_PORT -N$tunnel_comment -g
		
		cp $tunnelSrcDir/$tunnel_name $tunnelDoingDir/$tunnel_name
        info done.
    fi
	
done
